package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.Admin;
import com.tanhua.model.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public Map login(Map map) {
        //1、获取请求的参数（username,password,verificationCode（验证码）,uuid）
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String verificationCode = (String) map.get("verificationCode");
        String uuid = (String) map.get("uuid");
        //2、判断验证码是否正确
        String key = Constants.CAP_CODE + uuid;
        String value = redisTemplate.opsForValue().get(key); //从缓存中取出验证码
        if (StringUtils.isEmpty(value) || !verificationCode.equals(value)){//判断取出来的验证码是否为空，以及是否跟前端传过的验证码是否一致
            throw new BusinessException("验证码错误");
        }
            redisTemplate.delete(key);
        //3、根据用户名查询管理员admin
        QueryWrapper<Admin> qw = new QueryWrapper<Admin>().eq("username",username);
        Admin admin = adminMapper.selectOne(qw);
        //4、判断admin是否存在，密码是否一致
        password = SecureUtil.md5(password);//md5加密
        if (admin == null || !password.equals(admin.getPassword())){
            throw  new BusinessException("用户名或者密码");//用户名错误或者密码不一致
        }
        //5、通过JWT生成token
        Map tokenmap = new HashMap();
        tokenmap.put("username", admin.getUsername());
        tokenmap.put("id", admin.getId());
        String token = JwtUtils.getToken(tokenmap);
        //6、构造返回值
        Map retMap = new HashMap();
        retMap.put("token",token);
        return retMap;

    }

    /**
     * 获取当前用户的用户资料
     * @return
     */
    public AdminVo profile() {
        Long id = AdminHolder.getUserId();
        Admin admin = adminMapper.selectById(id);
        return AdminVo.init(admin);
    }

    /**
     * 退出登录
     */
    public void logout(String token) {
        redisTemplate.delete(token);

    }



}
